package cn.caojun.org.service.impl;

import cn.caojun.basic.query.BaseQuery;
import cn.caojun.basic.service.impl.BaseServiceImpl;
import cn.caojun.basic.utils.PageList;
import cn.caojun.org.domain.Department;
import cn.caojun.org.mapper.DepartmentMapper;
import cn.caojun.org.query.DepartmentQuery;
import cn.caojun.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    public void add(Department department) {
        department.setCreateTime(new Date());
        departmentMapper.insert(department);

        String path="";
        if (Objects.isNull(department.getDepartment().getId())){
            path="/"+department.getId();
        }else {
            Department department1=departmentMapper.loadById(department.getDepartment().getId());
            path=department1.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void removeById(Serializable id) {
        Department department = departmentMapper.loadById(id);
        List<Department> departmentList=departmentMapper.loadDepartmentByPath(department.getPath());
        String stringPath=department.getPath();
        for (int i=0;i<departmentList.size();i++){
            Department d1=departmentList.get(i);
            String str1=d1.getPath();
            String str2=str1.substring(str1.indexOf(stringPath)+stringPath.length(),str1.length());
            d1.setPath(str2);
            d1.setParentId(null);
            departmentList.set(i,d1);
        }
        for (Department de:departmentList) {
            departmentMapper.update(de);
        }
        departmentMapper.deleteById(id);
    }

    @Override
    public List<Department> getTree() {
        return departmentMapper.getTree();
    }

}
